import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyj
 * @date 2022年05月31日 9:18
 */
public class WriteExcel {
    public static void main(String[] args) {

        String fileName = "student.xlsx";
        String[] titles = {"ID", "name", "age"};
        List<Student> list = getStudents();
        OutputStream os = null;
        try {
            Workbook workbook = getWorkBook(fileName);
            Sheet sheet = workbook.createSheet("student");
            createTitle(sheet, titles);
            writeContent(sheet, list);
            os = new FileOutputStream(fileName);
            workbook.write(os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeContent(Sheet sheet, List<Student> list) {
        for (int i = 0; i < list.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Student student = list.get(i);
            Cell id = row.createCell(0);
            id.setCellType(CellType.NUMERIC);
            id.setCellValue(String.valueOf(student.getId()));
            Cell name = row.createCell(1);
            name.setCellValue(student.getName());
            Cell age = row.createCell(2);
            age.setCellValue(String.valueOf(student.getAge()));

        }
    }

    private static List<Student> getStudents() {

        List<Student> list = new ArrayList<>();
        list.add(new Student(1, "张三", 12));
        list.add(new Student(2, "李四", 23));
        list.add(new Student(3, "王五", 43));
        list.add(new Student(4, "张无忌", 13));
        list.add(new Student(5, "赵敏", 23));
        list.add(new Student(6, "谢逊", 32));
        return list;
    }

    private static void createTitle(Sheet sheet, String[] titles) {
        Row row = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
        }

    }

    private static Workbook getWorkBook(String fileName) {
        Workbook workbook = null;
        if (fileName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook();
        } else if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook();
        }

        return workbook;

    }
}
